//
//  XGOfflineDownloadViewModel.swift
//  TodayNews
//
//  Created by monkey on 2020/2/10.
//  Copyright © 2020 itcast. All rights reserved.
//

import UIKit
import SwiftyJSON

class XGOfflineDownloadViewModel
{
    /// 标题分类数组
    private(set) var newsCategories: [XGNewsCategoryModel]?
    /// 文件路径
    private var filePath: String = {
        let libraryPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first!
        return libraryPath + "/Preferences/newsCategories.data"
    }()
    
    /// 获取首页新闻分类数据
    /// - Parameter completionHandle: 完成回调
    func fetchNewsCategories(completionHandle: @escaping(Bool) -> Void) -> Void
    {
        // 字典转模型block
        let dictionaryToModelBlock = { (dataArray: [JSON]) -> Void in
            self.newsCategories = dataArray.compactMap {
                return XGNewsCategoryModel.deserialize(from: $0.dictionaryObject)
            }
            
            completionHandle(true)
        }
        
        if let result = loadNewsCategoriesFromCache() {
            // 缓存获取
            dictionaryToModelBlock(result)
        } else {
            // 网络获取
            AlamofireTool.loadNewsCategoriesData { (responseObject, error) in
                if responseObject == nil || error != nil {
                    XGPrint("加载新闻标题分类数据失败!")
                    completionHandle(false)
                    return
                }
                
                let jsonObject = JSON(responseObject!)
                guard let data = jsonObject["data"].dictionary,
                    let dataArray = data["data"]?.array else {
                        XGPrint("json解析错误")
                        completionHandle(false)
                        return
                }
                
                dictionaryToModelBlock(dataArray)
            }
        }
    }
    
    /// 更新数据模型
    /// - Parameters:
    ///   - index: 索引
    ///   - completionHandle: 完成回调
    func updateNewsCategoryModel(index: Int, completionHandle: () -> Void) -> Void
    {
        guard var newsCategoryModel = newsCategories?[index] else {
            return
        }
        
        newsCategoryModel.isSelected = !newsCategoryModel.isSelected
        newsCategories?[index] = newsCategoryModel
        completionHandle()
    }
    
    /// 保存新闻分类数组数据
    func saveNewsCategories() -> Void
    {
        guard let jsonStr = newsCategories?.toJSONString() else {
            return
        }
        
        try? jsonStr.write(toFile: filePath, atomically: true, encoding: .utf8)
        XGPrint(filePath)
    }
    
    /// 从本地加载新闻分类数组数据
    private func loadNewsCategoriesFromCache() -> [JSON]?
    {
        if FileManager.default.fileExists(atPath: filePath) {
            if let data = try? Data(contentsOf: URL(fileURLWithPath: filePath)) {
                let json = try? JSON(data: data)
                return json?.array
            }
        }
        
        return nil
    }
}
